package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@RestController
@RequestMapping("/login")
public class LoginController {

    @Reference
    MemberService memberService;

    @Autowired
    JedisPool jedisPool;

    /**
     * 步骤：
     *      1. 从map中取出验证码，取出手机号， 从redis取出验证码，校验
     *      2. 如果校验成功，判断你是否会员，如果不是，自动注册
     //     3. 把手机号存入cookie
            4. 返回页面
     * @param map
     * @return
     */
    @RequestMapping("/check")
    public Result check(@RequestBody Map<String,String> map, HttpServletResponse response){
        //1. 从map中取出验证码、取出手机号， 从redis取出验证码，校验
        String validateCode = map.get("validateCode");
        String telephone = map.get("telephone");
        //从redis取出验证码
        String validateCodeInRedis = jedisPool.getResource().get(RedisMessageConstant.SENDTYPE_LOGIN + "-" + telephone);
        //校验：用户输入的验证码与redis验证码比较
        if(validateCode == null || !validateCode.equals(validateCodeInRedis)){
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        //2. 判断是否是会员， 根据手机号查询会员，如果能查到，说明是会员；如不不能，自动注册会员
        Member member = memberService.findByTelephone(telephone);
        if(member == null){
            //不是会员，自动注册
            member = new Member();
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());
            //注册
            memberService.add(member);
        }
        //存入到cookie
        Cookie cookie = new Cookie("login_member_telephone", telephone);
        cookie.setMaxAge(60*60*24*30);
        cookie.setPath("/");
        response.addCookie(cookie);
        return new Result(true,MessageConstant.LOGIN_SUCCESS);
    }
}
